import java.util.List;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import dictionary.RadiusDict;


public class RadiusProtocolEncoder extends ProtocolEncoderAdapter {

	@Override
	public void encode(IoSession session, Object radiusMessage, ProtocolEncoderOutput out)
			throws Exception {
		System.out.println("start encoding");
		RadiusPacket pckt = (RadiusPacket) radiusMessage;
		IoBuffer buffer = IoBuffer.allocate(0, false).clear();
		buffer.setAutoExpand(true);
		buffer.setAutoShrink(true);
		buffer.putUnsigned((byte)pckt.getCode());
		buffer.putUnsigned((byte)pckt.getIdentifier());
		buffer.putUnsignedShort((short)pckt.getLength());
		buffer.put(pckt.getAuth());
		
		List<RadiusAttribute> avp = pckt.getAvpList();
		
		for (RadiusAttribute attr : avp) {
			buffer.put((byte)attr.getType());
			buffer.putUnsigned(attr.getLength());
		    buffer.put(attr.getValue());
		}
		
		buffer.flip();
		out.write(buffer);
		System.out.println("end encoding");
	}
}
